package com.jrx.anytxn.reporting.job.reportingFile.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.SftpUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.ReportingFileConfig;
import com.jrx.anytxn.reporting.config.SftpConfig;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.Arrays;
import java.util.List;

@Configuration
@EnableConfigurationProperties({SftpConfig.class, ReportingFileConfig.class})
public class ReportingFileUploadConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(ReportingFileUploadConfiguration.class);


    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private SftpConfig sftpConfig;
    @Autowired
    private ReportingFileConfig reportingFileConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;

    @Bean
    public Job reportingFileUploadJob() {
        return jobBuilderFactory.get("reportingFileUploadJob")
                .start(reportingFileUploadStep())
                .build();
    }

    @Bean
    public Step reportingFileUploadStep() {
        return stepBuilderFactory.get("reportingFileUploadStep")
                .tasklet(reportingFileUploadTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet reportingFileUploadTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.info("报送文件上传开始。。。。。。");

            String basePath = reportingFileConfig.getReportingFilePath();

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
            String today = DateUtils.format(org.getToday(),"yyyyMMdd");

            String filePath = basePath + org.getTenantId() + File.separator + today + File.separator;

            File file = new File(filePath);
            File[] tempList = file.listFiles();

            //1 获取连接
            SftpUtils.sftpConnect(sftpConfig.getUsername(),sftpConfig.getPassword(),sftpConfig.getHost(),sftpConfig.getPort());

            //2 检查创建目录
            String directory = sftpConfig.getUploadPath() + org.getTenantId() + "/" + today;
            SftpUtils.createDir(directory);

            //3 先上传TXT文件，再上传OK文件
            //原文件不删除，按照文件名判断是否需要上传
            List<String> txtFileLists = Arrays.asList(ReportingConstant.REPORTING_FILE_TYPE_CUSTOMER+"_"+today+".txt",
                    ReportingConstant.REPORTING_FILE_TYPE_LOAN+"_"+today+".txt",
                    ReportingConstant.REPORTING_FILE_TYPE_PAYMENT+"_"+today+".txt",
                    ReportingConstant.REPORTING_FILE_TYPE_PAYMENT_PLAN+"_"+today+".txt",
                    ReportingConstant.REPORTING_FILE_TYPE_LIMIT+"_"+today+".txt",
                    ReportingConstant.REPORTING_FILE_TYPE_STAGING+"_"+today+".txt");
            for(File uploadFile : tempList){
                String filename = uploadFile.getName();
                if(txtFileLists.contains(filename)){
                    SftpUtils.sftpUpload(uploadFile);
                }
            }
            logger.info("报送txt文件上传完成。。。。。。");
            String dataok = today + ".ok";
            List<String> okFileLists = Arrays.asList(ReportingConstant.REPORTING_FILE_TYPE_CUSTOMER+"_"+today+".ok",
                    ReportingConstant.REPORTING_FILE_TYPE_LOAN+"_"+today+".ok",
                    ReportingConstant.REPORTING_FILE_TYPE_PAYMENT+"_"+today+".ok",
                    ReportingConstant.REPORTING_FILE_TYPE_PAYMENT_PLAN+"_"+today+".ok",
                    ReportingConstant.REPORTING_FILE_TYPE_LIMIT+"_"+today+".ok",
                    ReportingConstant.REPORTING_FILE_TYPE_STAGING+"_"+today+".ok");

            for(File uploadFile : tempList){
                String filename = uploadFile.getName();
                if(dataok.equals(filename)){
                    continue;
                }
                if(okFileLists.contains(filename)){
                    SftpUtils.sftpUpload(uploadFile);
                }
            }
            logger.info("单个ok文件上传完成。。。。。。");

            for(File uploadFile : tempList){
                String filename = uploadFile.getName();
                if(dataok.equals(filename)){
                    SftpUtils.sftpUpload(uploadFile);
                    break;
                }
            }
            logger.info("日期ok文件上传完成。。。。。。");

            //关闭连接
            SftpUtils.disSftpConnect();

            logger.info("报送文件上传结束。。。。。。");
            return RepeatStatus.FINISHED;
        };
    }
}
